package jobhunter.repository;

import java.util.List;

import jobhunter.model.Company;
import jobhunter.model.User;
import jobhunter.security.SecurityContext;
import jobhunter.tool.JpaResultHelper;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@SuppressWarnings("unchecked")
public class UserRepository extends GenericRepositoryJpa<User>
{
	public UserRepository() {
		setEntityClass(User.class);
	}

	public User findByLogin(String login) 
	{
		return (User) JpaResultHelper.getSingleResultOrNull(em.createQuery("SELECT u FROM User u Where u.username = :login").setParameter("login", login));
	}
	public User findByUserName(String login) 
	{
		return findByLogin(login);
	}
	

	
	@Override
	public User merge(User t) {
		if(t==SecurityContext.getUser())
			return em.merge(t);
		else
			return null;
	}
	@Override
	public void remove(User t) 
	{
		if(t==SecurityContext.getUser())
			em.remove(t);		
	}
	
	

	public User findById(Long id) 	
	{ 
		return (User) JpaResultHelper.getSingleResultOrNull(em.createQuery("SELECT x FROM "+entityClass.getSimpleName()+" x  WHERE x.id=:id ")
				.setParameter("id", id));
	}

	public List<User> findByUser() 
	{
		return (List<User>) em.createQuery("SELECT x FROM "+entityClass.getSimpleName()+" x ORDER BY x.id")
				.getResultList();		
	}
}